import http from '../api/httpRequest.js'

export default {
	state: {
		regionGroups: [],
		activeRegionGroup: null,
	},
	mutations: {
		setRegionGroups(state, regionGroups) {
			state.regionGroups = regionGroups;
		},
		activeRegionGroup(state, idx) {
			state.activeRegionGroup = state.regionGroups[idx];
		},
		addRegionGroup(state, regionGroup) {
			state.regionGroups.unshift(regionGroup);
		},
		removeRegionGroup(state, regionGroupId) {
			state.regionGroups.forEach((g, idx) => {
				if (g.id == regionGroupId) {
					state.regionGroups.splice(idx, 1);
				}
			})
			if (state.activeRegionGroup.id == regionGroupId) {
				state.activeRegionGroup = null;
			}
		},
		updateRegionGroup(state, regionGroup) {
			state.regionGroups.forEach((g, idx) => {
				if (g.id == regionGroup.id) {
					// 拷贝属性
					Object.assign(state.regionGroups[idx], regionGroup);
				}
			})
		},
		clear(state) {
			state.regionGroups = [];
			state.activeRegionGroup = null;
		},
	},
	actions: {
		loadRegionGroup(context) {
			return new Promise((resolve, reject) => {
				http({
					url: '/region/group/list',
					method: 'GET'
				}).then((regionGroups) => {
					context.commit("setRegionGroups", regionGroups);
					console.log("loadRegionGroup")
					resolve();
				}).catch((res) => {
					reject(res);
				})
			});
		},
	}
}